<template>
  <input
    type="file"
    ref="imageRef"
    accept="image/*"
    style="display: none"
    multiple
    @change="imageChange"
  />
  <i title="图片" class="iconfont icon-tupian" @click="imageClick" />
</template>

<script setup>
import { getCurrentInstance, ref } from "vue";
import { useUserInfoStore } from "@/stores/UserInfoStore";

const { proxy } = getCurrentInstance();
const userInfoStore = useUserInfoStore();

const props = defineProps({
  contactId: {
    type: String,
  },
});

const imageRef = ref();
const imageClick = async () => {
  imageRef.value.click();
};
const imageChange = async (e) => {
  const prefix = props.contactId.substring(0, 1);
  if (e.target.files.length > 0) {
    if (e.target.files.length > 6) {
      proxy.$message.error("图片上限为6张");
      return;
    }
    const files = e.target.files;
    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
      formData.append("files", files[i]);
    }
    const resUpload = await proxy.Api.minioUploadFiles(formData);
    for (var i = 0; i < resUpload.data.length; i++) {
      if (prefix === "U") {
        const res = await proxy.Api.sendPrivateMessage({
          deduplicationId: proxy.UniqueId.generateUniqueUserId(),
          sendUserId: userInfoStore.getInfo().userId,
          contactId: props.contactId,
          messageType: "image",
          messageContent: resUpload.data[i],
          fileSize: files[i].size,
          fileName: files[i].name,
        });
        if (res.code == 114) {
          proxy.Confirm({
            message: res.message,
            okfun: () => {
              addContact(props.currentChatUser.contactId, res.code);
            },
            okText: "重新申请",
          });
        } else if (res.code == 200) {
          proxy.$message.success("图片已发送");
        }
      } else if (prefix === "G") {
        const res = await proxy.Api.sendClusterMessage({
          deduplicationId: proxy.UniqueId.generateUniqueClusterId(),
          sendUserId: userInfoStore.getInfo().userId,
          contactId: props.contactId,
          messageType: "image",
          messageContent: resUpload.data[i],
          fileSize: files[i].size,
          fileName: files[i].name,
        });
        if (res.code === 119) {
          proxy.Confirm({
            message: res.message,
            okfun: () => {
              addContact(props.currentChatUser.contactId, res.code);
            },
            okText: "重新申请",
          });
        } else if (res.code === 200) {
          proxy.$message.success("图片已发送");
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.iconfont {
  margin-left: 10px;
  cursor: pointer;
}
</style>
